import styled from "styled-components";
import { useState, useEffect } from "react";
import { Modal, Form, DatePicker, Cascader, message } from "antd";
import { Space, Table, Input, Button } from "antd";
const { Search } = Input;

const MyApp = styled.div`
  margin: 10px;
  padding: 0px;
`;

const Header = styled.div`
  margin: 10px;
  padding: 0px;
  text-align: center;
`;

const Query = () => {
  const [options, setOptions] = useState([{ value: "全部", label: "全部" }]);
  const [type, setType] = useState(["全部"]);
  const [data, setData] = useState();
  const [searchValue, setSearchValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [showAddModal, setShowAddModal] = useState(false);

  const handleSearch = (value) => {
    setSearchValue(value);
    fetchData(value); // 主动传递最新值
  };

  const onCascaderChange = () => {};

  const handleInputChange = (e) => {
    setSearchValue(e.target.value);
  };

  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/mapData/key/${searchValue}`, {
        method: "GET",
      });
      if (!response.ok) {
        throw new Error("网络连接失败！");
      }
      const result = await response.json();
      setData(result || []);
    } catch (error) {
      message.error("获取数据失败：" + error);
    } finally {
      setLoading(false);
    }
  };
  const handleAdd = async (values) => {
    try {
      const response = await fetch("/mapData", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });

      if (!response.ok) throw new Error("新增失败");

      message.success("新增成功");
      setShowAddModal(false);
      form.resetFields();
      fetchData(); // 刷新表格数据
    } catch (error) {
      message.error("新增失败: " + error.message);
    }
  };

  return (
    <MyApp>
      <Header>
        <Space style={{ gap: "8px" }}>
          <Cascader
            options={options}
            onChange={onCascaderChange}
            value={type}
            style={{ width: 100 }}
          />
          <Search
            placeholder="关键词"
            onSearch={handleSearch}
            onChange={handleInputChange}
            value={searchValue}
            enterButton
            style={{ width: 250 }}
          />
          <Button type="primary" onClick={() => setShowAddModal(true)}>
            新增数据
          </Button>
        </Space>
      </Header>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        scroll={{ x: 1200 }}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50"],
          showTotal: (total) => `共 ${total} 条`,
        }}
        size="small"
        style={{ marginTop: 10 }}
      />
      <Modal
        title="新增数据"
        open={showAddModal}
        onOk={() => form.submit()}
        onCancel={() => {
          setShowAddModal(false);
          form.resetFields();
        }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAdd}
          initialValues={{ type: "default" }}
        >
          <Form.Item
            label="键名"
            name="key"
            rules={[{ required: true, message: "键名必须填写" }]}
          >
            <Input placeholder="请输入唯一键名" />
          </Form.Item>

          <Form.Item label="存储值" name="value">
            <Input.TextArea rows={3} placeholder="请输入存储值" />
          </Form.Item>

          <Form.Item label="主分类" name="type">
            <Input placeholder="请输入主分类" />
          </Form.Item>

          <Form.Item label="子分类" name="subType">
            <Input placeholder="请输入子分类" />
          </Form.Item>

          <Form.Item label="标签" name="label">
            <Input placeholder="请输入可读标签" />
          </Form.Item>

          <Form.Item label="备注" name="note">
            <Input.TextArea rows={2} placeholder="请输入备注说明" />
          </Form.Item>
        </Form>
      </Modal>
    </MyApp>
  );
};

export default Query;

// 修改后的表格列配置
const columns = [
  {
    title: "键名",
    dataIndex: "key",
    width: 100,
    fixed: "left",
    sorter: true,
  },
  {
    title: "存储值",
    dataIndex: "value",
    width: 300,
  },
  {
    title: "分类",
    dataIndex: "type",
    width: 100,
    ellipsis: true,
  },
  {
    title: "标签",
    dataIndex: "label",
    width: 100,
    ellipsis: true,
  },
  {
    title: "更新时间",
    dataIndex: "insertTime",
    width: 100,
  },
];
